package com.ustc.hewei.rpc.client.net;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;

/**
 * @author hewei
 * @version 1.0
 * @description: netty客户端的自定义处理器
 * @date 2022/7/28 20:30
 */

@Slf4j
public class SendHandler extends ChannelInboundHandlerAdapter {
    //需要发送的请求数据
    private final byte[] data;

    private Object response = null;

    private final CountDownLatch latch;

    public SendHandler(byte[] data) {
        this.data = data;
        latch = new CountDownLatch(1);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ByteBuf buffer = Unpooled.buffer(data.length);
        buffer.writeBytes(data);
        ctx.writeAndFlush(buffer);
        log.info("客户端请求发送成功！{}", data);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf revive = (ByteBuf) msg;
        byte[] resp = new byte[revive.readableBytes()];
        revive.readBytes(resp);

        //不加这个有可能会报错
        revive.release();
        response = resp;
        latch.countDown();
    }

    public Object getResponse() throws InterruptedException {
        latch.await();
        return response;
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error(cause.getMessage());
        ctx.close();
    }
}
